package com.bo.shiro;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.bo.common.lang.Result;
import com.bo.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtFilter extends AuthenticatingFilter {
    //注入JwtUtils
    @Autowired
    JwtUtils jwtUtils;

    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        //获取jwt并封装进Token
        //强转为HttpServletRequest
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        //从请求的header中获取授权信息，并封装进Token
        String jwt = request.getHeader("Authorization");
        if(jwt.isEmpty()){
            return null;
        }

        return new JwtToken(jwt);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        //获取jwt并封装进Token
        //强转为HttpServletRequest
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        //从请求的header中获取授权信息，并封装进Token
        String jwt = request.getHeader("Authorization");
        if(!StringUtils.hasLength(jwt)){
            //若jwt为空则不需要交给shiro进行处理，可以直接访问controller，即不需要进行拦截
            return true;
        }else{
            //校验jwt
            Claims claims = jwtUtils.getClaimByToken(jwt);
            if(claims == null || jwtUtils.isTokenExpired(claims.getExpiration())){
                throw new ExpiredCredentialsException("登陆失败！");
            }

            //执行登陆
            return executeLogin(servletRequest, servletResponse);
        }
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletResponse httpServletResponse = (HttpServletResponse)response;

        //获取错误原因
        Throwable throwable = e.getCause()==null ?  e : e.getCause();

        //将错误原因返回到前端
        //设置错误原因
        Result fail = Result.fail(throwable.getMessage());
        //将错误信息设置为jsong格式
        String json = JSONUtil.toJsonStr(fail);

        try {
            httpServletResponse.getWriter().print(json);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return false;
    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        //跨域时会首先发送一个OPTIONS请求，这里我们给OPTIONS请求直接返回正常状态
        if(httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())){
            httpServletResponse.setStatus(HttpStatus.OK.value());
        }

        return super.preHandle(request, response);
    }
}
